package com.swan.test.context;

import com.swan.test.constant.LogConstant;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author zongf
 * @date 2024-02-04
 **/
public class LogContext {

    private static ThreadLocal<String> logIdHolder = new ThreadLocal<>();

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSSS");


    /** 自动生成logId, 并设置
     * @return
     */
    public static String setLogId() {

        String random = UUID.randomUUID().toString().replaceAll("-", "");
        String logId = sdf.format(new Date()) + random;
        setLogId(logId);

        return logId;
    }

    public static void setLogId(String logId) {
        if (StringUtils.hasText(logId)) {
            logIdHolder.set(logId);
            MDC.put(LogConstant.LOG_ID, logId);
        }
    }

    public static String getLogId() {
        return logIdHolder.get();
    }

    public static void cleanLodId() {
        MDC.remove(LogConstant.LOG_ID);
    }

}
